<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-key"></i>
              Ansible凭据管理
            </h1>
            <p class="page-subtitle">管理Ansible连接凭据和认证信息</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">凭据总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ stats.active }}</div>
              <div class="stat-label">活跃凭据</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ stats.securityRate }}</div>
              <div class="stat-label">安全率</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="search-filters glass-effect">
        <el-form inline class="search-form">
          <el-form-item>
            <el-button type="primary" @click="addCredential" class="glass-button add-button">
              <i class="fa fa-plus"></i>
              添加凭据
            </el-button>
            <el-button @click="refreshCredentials" class="glass-button refresh-button" :loading="loading">
              <i class="fa fa-refresh"></i>
              刷新列表
            </el-button>
            <el-button @click="testAllCredentials" class="glass-button test-button">
              <i class="fa fa-check-circle"></i>
              批量测试
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 凭据列表 -->
      <div class="audit-table-section glass-effect">
        <div class="section-title">
          <i class="fa fa-list"></i>
          凭据列表
        </div>

        <el-table
          :data="credentials"
          style="width: 100%"
          v-loading="loading"
          @row-click="viewCredentialDetail"
          row-class-name="audit-row"
          class="audit-table"
        >
          <el-table-column prop="name" label="凭据名称" min-width="150">
            <template #default="scope">
              <div class="config-name">
                <i class="fa fa-key"></i>
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="credential_type" label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeColor(scope.row.credential_type)" size="small">
                {{ getTypeText(scope.row.credential_type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" width="120" />

          <el-table-column prop="is_active" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.is_active ? 'success' : 'info'" size="small">
                {{ scope.row.is_active ? '活跃' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="last_used" label="最后使用" width="160">
            <template #default="scope">
              {{ formatTime(scope.row.last_used) }}
            </template>
          </el-table-column>

          <el-table-column prop="created_at" label="创建时间" width="160">
            <template #default="scope">
              {{ formatTime(scope.row.created_at) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="480" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" @click.stop="viewCredentialDetail(scope.row)" class="action-glass-button">
                  <i class="fa fa-eye"></i>
                  详情
                </el-button>
                <el-button size="small" @click.stop="editCredential(scope.row)" class="action-glass-button edit-action">
                  <i class="fa fa-edit"></i>
                  编辑
                </el-button>
                <el-button size="small" @click.stop="testCredential(scope.row)" class="action-glass-button test-action">
                  <i class="fa fa-flask"></i>
                  测试
                </el-button>
                <el-button
                  size="small"
                  @click.stop="deleteCredential(scope.row)"
                  class="action-glass-button danger"
                >
                  <i class="fa fa-trash"></i>
                  删除
                </el-button>
                <el-button
                  v-if="scope.row.credential_type === 'ssh_key'"
                  size="small"
                  @click.stop="pushPublicKey(scope.row)"
                  class="action-glass-button push-action"
                >
                  <i class="fa fa-upload"></i>
                  推送公钥
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 返回按钮 -->
      <div class="action-section">
        <el-button @click="goBack" class="glass-button primary" size="large">
          <i class="fa fa-arrow-left"></i>
          返回
        </el-button>
      </div>
    </div>

    <!-- 凭据创建/编辑对话框 -->
    <el-dialog
      v-model="showCredentialDialog"
      :title="credentialForm.id ? '编辑凭据' : '创建凭据'"
      width="600px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="credentialForm" label-width="120px" class="credential-form">
        <el-form-item label="凭据名称" required>
          <el-input v-model="credentialForm.name" placeholder="请输入凭据名称" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="credentialForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入凭据描述（可选）"
          />
        </el-form-item>

        <el-form-item label="凭据类型" required>
          <el-select v-model="credentialForm.credential_type" placeholder="请选择凭据类型" style="width: 100%">
            <el-option label="用户名密码" value="password" />
            <el-option label="SSH密钥" value="ssh_key" />
            <el-option label="AWS访问密钥" value="aws_key" />
            <el-option label="Ansible Vault" value="vault" />
          </el-select>
        </el-form-item>

        <!-- 用户名密码类型 -->
        <template v-if="credentialForm.credential_type === 'password'">
          <el-form-item label="用户名" required>
            <el-input v-model="credentialForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" required>
            <el-input
              v-model="credentialForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
        </template>

        <!-- SSH密钥类型 -->
        <template v-if="credentialForm.credential_type === 'ssh_key'">
          <el-form-item label="用户名" required>
            <el-input v-model="credentialForm.username" placeholder="请输入SSH用户名" />
          </el-form-item>
          <el-form-item label="公钥" required>
            <el-input
              v-model="credentialForm.public_key"
              type="textarea"
              :rows="4"
              placeholder="请粘贴SSH公钥内容（用于推送到目标服务器）"
            />
          </el-form-item>
          <el-form-item label="私钥">
            <el-input
              v-model="credentialForm.private_key"
              type="textarea"
              :rows="6"
              placeholder="请粘贴SSH私钥内容（可选，仅在需要SSH连接时使用）"
            />
          </el-form-item>
        </template>

        <!-- AWS密钥类型 -->
        <template v-if="credentialForm.credential_type === 'aws_key'">
          <el-form-item label="Access Key ID" required>
            <el-input v-model="credentialForm.access_key_id" placeholder="请输入AWS Access Key ID" />
          </el-form-item>
          <el-form-item label="Secret Access Key" required>
            <el-input
              v-model="credentialForm.secret_access_key"
              type="password"
              placeholder="请输入AWS Secret Access Key"
              show-password
            />
          </el-form-item>
        </template>

        <!-- Vault密码类型 -->
        <template v-if="credentialForm.credential_type === 'vault'">
          <el-form-item label="Vault密码" required>
            <el-input
              v-model="credentialForm.vault_password"
              type="password"
              placeholder="请输入Ansible Vault密码"
              show-password
            />
          </el-form-item>
        </template>

        <el-form-item label="状态">
          <el-switch
            v-model="credentialForm.is_active"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCredentialDialog = false" class="action-glass-button">
            取消
          </el-button>
          <el-button type="primary" @click="saveCredential" class="action-glass-button">
            {{ credentialForm.id ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 推送公钥对话框 -->
    <el-dialog
      v-model="showPushKeyDialog"
      title="推送SSH公钥"
      width="800px"
      class="glass-dialog"
      :close-on-click-modal="false">
      <div class="push-key-form">
        <el-form :model="pushKeyForm" label-width="120px">
          <el-form-item label="凭据信息">
            <div class="credential-info glass-effect">
              <div class="info-item">
                <span class="label">凭据名称:</span>
                <span class="value">{{ selectedCredential?.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户名:</span>
                <span class="value">{{ selectedCredential?.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">公钥指纹:</span>
                <span class="value">{{ getPublicKeyFingerprint(selectedCredential?.public_key) }}</span>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="目标用户名" required>
            <el-input
              v-model="pushKeyForm.target_username"
              placeholder="要推送到的目标主机用户名"
              class="glass-input">
            </el-input>
          </el-form-item>

          <el-form-item label="认证方式" required>
            <el-radio-group v-model="pushKeyForm.auth_method">
              <el-radio value="password">密码认证</el-radio>
              <el-radio value="existing_key">现有密钥认证</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="pushKeyForm.auth_method === 'password'"
            label="认证密码"
            required>
            <el-input
              v-model="pushKeyForm.auth_password"
              type="password"
              placeholder="用于连接目标主机的密码"
              class="glass-input"
              show-password>
            </el-input>
          </el-form-item>

          <el-form-item
            v-if="pushKeyForm.auth_method === 'existing_key'"
            label="认证凭据"
            required>
            <el-select
              v-model="pushKeyForm.auth_credential_id"
              placeholder="选择用于认证的SSH密钥凭据"
              class="glass-select"
              style="width: 100%">
              <el-option
                v-for="cred in sshKeyCredentials"
                :key="cred.id"
                :label="`${cred.name} (${cred.username})`"
                :value="cred.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目标主机">
            <div class="transfer-wrapper">
              <el-transfer
                v-model="pushKeyForm.selected_hosts"
                :data="availableHosts"
                :titles="['可用主机', '选中主机']"
                :button-texts="['移除', '添加']"
                :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
                class="glass-transfer">
              </el-transfer>
            </div>
          </el-form-item>

          <el-form-item label="目标主机组">
            <el-select
              v-model="pushKeyForm.selected_groups"
              multiple
              placeholder="选择主机组（可选）"
              class="glass-select"
              style="width: 100%">
              <el-option
                v-for="group in availableGroups"
                :key="group.id"
                :label="group.name"
                :value="group.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPushKeyDialog = false" class="action-glass-button">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="executePushKey"
            :loading="pushKeyLoading"
            class="action-glass-button">
            <i class="fa fa-upload"></i>
            开始推送
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 推送结果对话框 -->
    <el-dialog
      v-model="showPushResultDialog"
      title="公钥推送结果"
      width="700px"
      class="glass-dialog">
      <div class="push-results">
        <div class="result-summary glass-effect">
          <div class="summary-item">
            <span class="label">总计:</span>
            <span class="value">{{ pushResults.total }}</span>
          </div>
          <div class="summary-item success">
            <span class="label">成功:</span>
            <span class="value">{{ pushResults.success }}</span>
          </div>
          <div class="summary-item failed">
            <span class="label">失败:</span>
            <span class="value">{{ pushResults.failed }}</span>
          </div>
        </div>

        <div class="result-details">
          <el-table :data="pushResults.results" class="glass-table">
            <el-table-column prop="hostname" label="主机名" width="150"></el-table-column>
            <el-table-column prop="ip" label="IP地址" width="150"></el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.success ? 'success' : 'danger'">
                  {{ scope.row.success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="详细信息"></el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPushResultDialog = false" class="action-glass-button">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ansibleAPI } from '@/api/ansible'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const showCredentialDetail = ref(false)
const showCredentialDialog = ref(false)
const selectedCredential = ref(null)
const credentials = ref([])

// 推送公钥相关数据
const showPushKeyDialog = ref(false)
const showPushResultDialog = ref(false)
const pushKeyLoading = ref(false)
const availableHosts = ref([])
const availableGroups = ref([])
const sshKeyCredentials = ref([])
const pushKeyForm = reactive({
  target_username: 'root',
  auth_method: 'password',
  auth_password: '',
  auth_credential_id: null,
  selected_hosts: [],
  selected_groups: []
})
const pushResults = reactive({
  total: 0,
  success: 0,
  failed: 0,
  results: []
})

const credentialForm = reactive({
  id: null,
  name: '',
  description: '',
  credential_type: 'password',
  username: '',
  password: '',
  private_key: '',
  public_key: '',
  access_key_id: '',
  secret_access_key: '',
  vault_password: '',
  is_active: true
})

// 统计数据
const stats = reactive({
  total: 0,
  active: 0,
  securityRate: '100%'
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 方法
const loadCredentials = async () => {
  loading.value = true
  try {
    const response = await ansibleAPI.getCredentials({
      page: pagination.currentPage,
      page_size: pagination.pageSize
    })

    console.log('API响应:', response.data)

    // 处理DRF标准分页响应格式
    if (response.data.results) {
      credentials.value = response.data.results
      pagination.total = response.data.count || 0
    } else if (Array.isArray(response.data)) {
      // 如果直接返回数组
      credentials.value = response.data
      pagination.total = response.data.length
    } else {
      // 如果是包装格式
      credentials.value = response.data.data?.results || response.data.data || []
      pagination.total = response.data.data?.count || credentials.value.length
    }

    // 更新统计数据
    updateStats()
    console.log('加载凭据成功，数量:', credentials.value.length)
  } catch (error) {
    console.error('加载凭据列表失败:', error)
    ElMessage.error(`加载凭据列表失败: ${error.message || error}`)
  } finally {
    loading.value = false
  }
}

const updateStats = () => {
  stats.total = credentials.value.length
  stats.active = credentials.value.filter(c => c.is_active).length
  stats.securityRate = stats.total > 0 ? Math.round((stats.active / stats.total) * 100) + '%' : '100%'
}

const addCredential = () => {
  resetCredentialForm()
  showCredentialDialog.value = true
}

const resetCredentialForm = () => {
  Object.assign(credentialForm, {
    id: null,
    name: '',
    description: '',
    credential_type: 'password',
    username: '',
    password: '',
    private_key: '',
    public_key: '',
    access_key_id: '',
    secret_access_key: '',
    vault_password: '',
    is_active: true
  })
}

const refreshCredentials = () => {
  loadCredentials()
  ElMessage.success('凭据列表已刷新')
}

const testAllCredentials = async () => {
  try {
    loading.value = true
    ElMessage.info('开始批量测试凭据...')

    const response = await ansibleAPI.testAllCredentials()
    console.log('批量测试响应:', response.data)

    const isSuccess = response.data.status === 'success' || response.status === 200

    if (isSuccess) {
      const data = response.data.data || response.data
      const { total, success, failed } = data
      ElMessage.success(`批量测试完成：成功 ${success}/${total}，失败 ${failed}`)
      // 刷新列表以更新最后使用时间
      loadCredentials()
    } else {
      ElMessage.error(response.data.message || '批量测试失败')
    }
  } catch (error) {
    console.error('批量测试失败:', error)
    ElMessage.error(`批量测试失败: ${error.response?.data?.message || error.message || error}`)
  } finally {
    loading.value = false
  }
}

const viewCredentialDetail = (credential) => {
  selectedCredential.value = credential
  showCredentialDetail.value = true
  ElMessage.info(`查看凭据详情: ${credential.name}`)
}

const editCredential = async (credential) => {
  try {
    // 获取完整的凭据详情
    const response = await ansibleAPI.getCredentialDetail(credential.id)
    console.log('获取凭据详情响应:', response.data)

    // 处理不同的响应格式
    const credentialData = response.data.data || response.data

    if (credentialData && credentialData.id) {
      Object.assign(credentialForm, {
        id: credentialData.id,
        name: credentialData.name,
        description: credentialData.description || '',
        credential_type: credentialData.credential_type,
        username: credentialData.username || '',
        password: '', // 密码不回显
        private_key: '', // 私钥不回显
        public_key: credentialData.public_key || '',
        access_key_id: credentialData.access_key_id || '',
        secret_access_key: '', // 密钥不回显
        vault_password: '', // 密码不回显
        is_active: credentialData.is_active
      })
      showCredentialDialog.value = true
    } else {
      ElMessage.error('获取凭据详情失败')
    }
  } catch (error) {
    console.error('获取凭据详情失败:', error)
    ElMessage.error(`获取凭据详情失败: ${error.response?.data?.message || error.message || error}`)
  }
}

const testCredential = async (credential) => {
  try {
    ElMessage.info(`正在测试凭据: ${credential.name}`)

    const response = await ansibleAPI.testCredential(credential.id)
    console.log('测试凭据响应:', response.data)

    const isSuccess = response.data.status === 'success' || response.status === 200
    const message = response.data.message || '测试完成'

    if (isSuccess) {
      ElMessage.success(`凭据 "${credential.name}" 测试成功: ${message}`)
      // 刷新列表以更新最后使用时间
      loadCredentials()
    } else {
      ElMessage.error(`凭据 "${credential.name}" 测试失败: ${message}`)
    }
  } catch (error) {
    console.error('测试凭据失败:', error)
    ElMessage.error(`测试凭据 "${credential.name}" 失败: ${error.response?.data?.message || error.message || error}`)
  }
}

// 推送公钥相关方法
const pushPublicKey = async (credential) => {
  try {
    selectedCredential.value = credential

    // 重置表单
    Object.assign(pushKeyForm, {
      target_username: 'root',
      auth_method: 'password',
      auth_password: '',
      auth_credential_id: null,
      selected_hosts: [],
      selected_groups: []
    })

    // 加载推送目标和SSH密钥凭据
    await loadPushTargets()
    await loadSshKeyCredentials()

    showPushKeyDialog.value = true
  } catch (error) {
    console.error('准备推送公钥失败:', error)
    ElMessage.error(`准备推送公钥失败: ${error.message}`)
  }
}

const loadPushTargets = async () => {
  try {
    const response = await ansibleAPI.getPushTargets()
    console.log('获取推送目标响应:', response.data)

    if (response.data.status === 'success') {
      // 转换主机数据格式
      availableHosts.value = response.data.data.hosts.map(host => ({
        key: host.id,
        label: `${host.hostname} (${host.public_ip || host.private_ip})`,
        disabled: false
      }))

      availableGroups.value = response.data.data.groups
    }
  } catch (error) {
    console.error('获取推送目标失败:', error)
    ElMessage.error(`获取推送目标失败: ${error.response?.data?.message || error.message}`)
  }
}

const loadSshKeyCredentials = async () => {
  try {
    // 获取所有SSH密钥类型的凭据
    sshKeyCredentials.value = credentials.value.filter(cred =>
      cred.credential_type === 'ssh_key' && cred.id !== selectedCredential.value?.id
    )
  } catch (error) {
    console.error('获取SSH密钥凭据失败:', error)
  }
}

const executePushKey = async () => {
  try {
    // 验证表单
    if (!pushKeyForm.target_username) {
      ElMessage.error('请输入目标用户名')
      return
    }

    if (pushKeyForm.auth_method === 'password' && !pushKeyForm.auth_password) {
      ElMessage.error('请输入认证密码')
      return
    }

    if (pushKeyForm.auth_method === 'existing_key' && !pushKeyForm.auth_credential_id) {
      ElMessage.error('请选择认证凭据')
      return
    }

    if (pushKeyForm.selected_hosts.length === 0 && pushKeyForm.selected_groups.length === 0) {
      ElMessage.error('请选择至少一个目标主机或主机组')
      return
    }

    pushKeyLoading.value = true

    const requestData = {
      target_username: pushKeyForm.target_username,
      auth_method: pushKeyForm.auth_method,
      host_ids: pushKeyForm.selected_hosts,
      group_ids: pushKeyForm.selected_groups
    }

    if (pushKeyForm.auth_method === 'password') {
      requestData.auth_password = pushKeyForm.auth_password
    } else if (pushKeyForm.auth_method === 'existing_key') {
      requestData.auth_credential_id = pushKeyForm.auth_credential_id
    }

    const response = await ansibleAPI.pushPublicKey(selectedCredential.value.id, requestData)
    console.log('推送公钥响应:', response.data)

    if (response.data.status === 'success') {
      // 显示推送结果
      Object.assign(pushResults, response.data.data)
      showPushKeyDialog.value = false
      showPushResultDialog.value = true

      ElMessage.success(response.data.message)
    } else {
      ElMessage.error(response.data.message || '推送失败')
    }
  } catch (error) {
    console.error('推送公钥失败:', error)
    ElMessage.error(`推送公钥失败: ${error.response?.data?.message || error.message}`)
  } finally {
    pushKeyLoading.value = false
  }
}

const getPublicKeyFingerprint = (publicKey) => {
  if (!publicKey) return '无'
  // 简单的指纹显示，取公钥的前20个字符
  const keyPart = publicKey.split(' ')[1] || publicKey
  return keyPart.substring(0, 20) + '...'
}

const deleteCredential = async (credential) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除凭据 "${credential.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    const response = await ansibleAPI.deleteCredential(credential.id)
    console.log('删除凭据响应:', response)

    // 删除成功通常返回204状态码
    const isSuccess = response.status === 204 || response.status === 200 || response.data?.status === 'success'

    if (isSuccess) {
      ElMessage.success(`凭据 "${credential.name}" 已删除`)
      loadCredentials() // 重新加载列表
    } else {
      ElMessage.error(response.data?.message || '删除凭据失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除凭据失败:', error)
      ElMessage.error(`删除凭据失败: ${error.response?.data?.message || error.message || error}`)
    }
  }
}

const saveCredential = async () => {
  try {
    // 验证必填字段
    if (!credentialForm.name.trim()) {
      ElMessage.error('请输入凭据名称')
      return
    }

    // SSH密钥类型验证
    if (credentialForm.credential_type === 'ssh_key') {
      if (!credentialForm.username.trim()) {
        ElMessage.error('请输入SSH用户名')
        return
      }
      if (!credentialForm.public_key.trim()) {
        ElMessage.error('请输入SSH公钥内容')
        return
      }
    }

    const isEdit = !!credentialForm.id
    const apiCall = isEdit
      ? ansibleAPI.updateCredential(credentialForm.id, credentialForm)
      : ansibleAPI.createCredential(credentialForm)

    const response = await apiCall
    console.log('保存凭据响应:', response.data)

    // 处理不同的响应格式
    const isSuccess = response.data.status === 'success' || response.status === 200 || response.status === 201
    const message = response.data.message || `凭据${isEdit ? '更新' : '创建'}成功`

    if (isSuccess) {
      ElMessage.success(message)
      showCredentialDialog.value = false
      loadCredentials() // 重新加载列表
    } else {
      ElMessage.error(response.data.message || `${isEdit ? '更新' : '创建'}凭据失败`)
    }
  } catch (error) {
    console.error('保存凭据失败:', error)
    ElMessage.error(`保存凭据失败: ${error.response?.data?.message || error.message || error}`)
  }
}

const getTypeColor = (type) => {
  const colors = {
    ssh_key: 'primary',
    password: 'success',
    aws_key: 'warning',
    vault: 'info'
  }
  return colors[type] || 'info'
}

const getTypeText = (type) => {
  const texts = {
    ssh_key: 'SSH密钥',
    password: '用户名密码',
    aws_key: 'AWS访问密钥',
    vault: 'Ansible Vault'
  }
  return texts[type] || '未知'
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadCredentials()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadCredentials()
}

const formatTime = (time) => {
  if (!time) return '未知'
  return new Date(time).toLocaleString()
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  loadCredentials()
})
</script>

<style lang="scss" scoped>
/* 复制ansible日志审计的完整样式 */
.ansible-audit-container {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 40, 0.95) 50%, rgba(0, 0, 0, 0.9) 100%);
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image: radial-gradient(2px 2px at 20px 30px, #eee, transparent), radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent), radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image: radial-gradient(1px 1px at 40px 60px, #fff, transparent), radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image: radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section {
  flex: 1;
}

.page-title {
  color: #00eaff;
  font-size: 2.5em;
  margin: 0 0 10px 0;
  text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  display: flex;
  align-items: center;
  gap: 15px;

  i {
    font-size: 0.8em;
  }
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.1em;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;

  .stat-number {
    color: #00eaff;
    font-size: 2em;
    font-weight: bold;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  }

  .stat-label {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.9em;
    margin-top: 5px;
  }
}

.search-filters {
  margin-bottom: 30px;
  padding: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 15px;
}

.audit-table-section {
  margin-bottom: 30px;
  padding: 30px;
}

.section-title {
  color: #00eaff;
  font-size: 1.3em;
  margin-bottom: 20px;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格单元格对齐 */
:deep(.el-table .cell) {
  text-align: left !important;
}

.config-name {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  color: rgba(255, 255, 255, 0.9);
  text-align: left;

  i {
    color: #00eaff;
    flex-shrink: 0;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-section {
  text-align: center;
  margin-top: 40px;
}

.glass-button {
  background: rgba(164, 244, 186, 0.8) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: white !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  box-shadow: 0 2px 8px rgba(164, 244, 186, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 1) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(164, 244, 186, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
  }

  &.primary {
    background: rgba(0, 234, 255, 0.8) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    box-shadow: 0 2px 8px rgba(0, 234, 255, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

    &:hover {
      background: rgba(0, 234, 255, 1) !important;
      border-color: rgba(0, 234, 255, 0.5) !important;
      box-shadow: 0 4px 12px rgba(0, 234, 255, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
    }
  }
}

@media (max-width: 1200px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }

  .stats-section {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .stats-section {
    flex-direction: column;
    gap: 15px;
  }
}

/* 凭据对话框样式 */
.credential-form {
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input, .el-select, .el-textarea {
    .el-input__wrapper, .el-select__wrapper, .el-textarea__inner {
      background: rgba(164, 244, 186, 0.1) !important;
      border: 1px solid rgba(164, 244, 186, 0.3) !important;
      color: white !important;
    }

    .el-input__inner, .el-select__input {
      color: white !important;
    }
  }

  .el-form-item__label {
    color: rgba(255, 255, 255, 0.9) !important;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 对话框玻璃效果 */
:deep(.el-dialog) {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  backdrop-filter: blur(20px) !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
  padding: 20px 20px 15px 20px !important;
}

:deep(.el-dialog__title) {
  color: #00eaff !important;
  font-size: 1.2em !important;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
}

:deep(.el-dialog__body) {
  padding: 20px !important;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid rgba(164, 244, 186, 0.2) !important;
  padding: 15px 20px 20px 20px !important;
}

/* 工具栏按钮样式 - 与inventory页面保持一致 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }

  /* 添加按钮 - 绿色 */
  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  /* 刷新按钮 - 紫色 */
  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
      box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  /* 测试按钮 - 蓝色 */
  &.test-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-start;
}

/* 操作按钮样式 - 带漂亮颜色 */
.action-glass-button {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  padding: 6px 10px !important;
  font-size: 12px !important;
  transition: all 0.3s ease !important;
  min-width: 60px !important;
  white-space: nowrap !important;

  &:hover {
    background: rgba(164, 244, 186, 0.2) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: rgba(255, 255, 255, 1) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(164, 244, 186, 0.3) !important;
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 2px 6px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 3px !important;
    font-size: 11px !important;
  }

  /* 编辑按钮 - 蓝色 */
  &.edit-action {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4) !important;
    }
  }

  /* 测试按钮 - 绿色 */
  &.test-action {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 12px rgba(34, 197, 94, 0.4) !important;
    }
  }

  /* 推送公钥按钮 - 青色 */
  &.push-action {
    background: rgba(6, 182, 212, 0.2) !important;
    border-color: rgba(6, 182, 212, 0.4) !important;
    color: #ffffff !important;
    min-width: 80px !important;
    padding: 6px 12px !important;

    &:hover {
      background: rgba(6, 182, 212, 0.3) !important;
      border-color: rgba(6, 182, 212, 0.6) !important;
      box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4) !important;
    }
  }

  /* 删除按钮 - 红色 */
  &.danger {
    background: rgba(255, 107, 107, 0.2) !important;
    border-color: rgba(255, 107, 107, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(255, 107, 107, 0.3) !important;
      border-color: rgba(255, 107, 107, 0.6) !important;
      color: #ffffff !important;
      box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4) !important;
    }
  }
}

/* 推送公钥对话框样式 */
.push-key-form {
  max-height: 600px;
  overflow-y: auto;
}

.credential-info {
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}

.credential-info .info-item {
  display: flex;
  margin-bottom: 8px;
}

.credential-info .label {
  font-weight: bold;
  color: #00eaff;
  min-width: 100px;
  margin-right: 10px;
}

.credential-info .value {
  color: #a4f4ba;
  font-family: monospace;
}

.push-results {
  max-height: 500px;
  overflow-y: auto;
}

.result-summary {
  display: flex;
  justify-content: space-around;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.summary-item {
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 14px;
  color: #00eaff;
  margin-bottom: 5px;
}

.summary-item .value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
}

.summary-item.success .value {
  color: #67c23a;
}

.summary-item.failed .value {
  color: #f56c6c;
}

.result-details {
  margin-top: 20px;
}

/* Transfer组件包裹框样式 */
:deep(.transfer-wrapper) {
  margin-top: 20px !important;
  margin-left: -10px !important;
  position: relative;
}

/* Transfer组件样式 */
:deep(.el-transfer) {
  display: flex;
  align-items: center;
}

:deep(.el-transfer-panel) {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 8px !important;
}

:deep(.el-transfer-panel__header) {
  background: rgba(164, 244, 186, 0.05) !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
  color: #00eaff !important;
}

:deep(.el-transfer-panel__body) {
  background: transparent !important;
}

:deep(.el-transfer-panel__item) {
  color: #a4f4ba !important;
  background: transparent !important;
}

:deep(.el-transfer-panel__item:hover) {
  background: rgba(164, 244, 186, 0.1) !important;
}

:deep(.el-transfer__buttons) {
  padding: 0 20px;
}

:deep(.el-transfer__button) {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: #00eaff !important;
  border-radius: 6px !important;
}

:deep(.el-transfer__button:hover) {
  background: rgba(164, 244, 186, 0.2) !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
}

/* 完全隐藏所有滚动条但保留滚动功能 */
:deep(.el-transfer-panel__list::-webkit-scrollbar) {
  display: none !important;
}

:deep(.el-transfer-panel__list) {
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}

/* 隐藏弹窗的滚动条 */
:deep(.el-dialog__body::-webkit-scrollbar) {
  display: none !important;
}

:deep(.el-dialog__body) {
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}

/* 隐藏表单容器的滚动条 */
:deep(.push-key-form::-webkit-scrollbar) {
  display: none !important;
}

.push-key-form {
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}
</style>
